package cn.comon.app.scan.service.analysis.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.comon.app.scan.component.SysConfigBean;
import cn.comon.app.scan.controller.AppScanController;
import cn.comon.app.scan.entity.AsCheckresult;
import cn.comon.app.scan.entity.AsReportinfo;
import cn.comon.app.scan.service.AsCheckresultService;
import cn.comon.app.scan.service.AsReportinfoService;
import cn.comon.app.scan.service.analysis.IAnalysisScanResult;
import cn.comon.app.scan.util.UtilTools;
@Service("dubaAnalysisScanResultImpl")
@Transactional
public class DubaAnalysisScanResultImpl implements IAnalysisScanResult {
    @Autowired
    private AsReportinfoService asReportinfoServiceImpl;;
    @Autowired
    private AsCheckresultService asCheckresultServiceImpl;
    private static Logger logger = Logger.getLogger(DubaAnalysisScanResultImpl.class.getName());
    
    private JSONObject saveScanResult(AsCheckresult asCheckresult, AsReportinfo asReportinfo) {
        //检索AsCheckresult表，确认该条记录是否曾经被同一家检测方检测过
        //记录不存在，插入新记录
        //记录存在，更新检测信息
        AsCheckresult asCheckresultTMP =
            asCheckresultServiceImpl.findByRidAndResultIndex(asCheckresult);
        if (asCheckresultTMP == null) {
            asCheckresultServiceImpl.addObj(asCheckresult);
        } else {
            asCheckresultServiceImpl.updateCheckresult(asCheckresult);
        }
        
        asReportinfoServiceImpl.updateReportinfo(asReportinfo);
        return new JSONObject();
    }
    
	public JSONObject checkResult(JSONObject resultData) {
	    JSONArray jsonArray = resultData.getJSONArray("resultList");
        for (int i = 0 ;i < jsonArray.size(); i++) {
            JSONObject jsonObj1 = jsonArray.getJSONObject(i);
            if (jsonObj1.getInt("error") == 0) {
                AsCheckresult asCheckresult = new AsCheckresult();
                //通过返回的sid,检索reportinfo表里对应的记录
                AsReportinfo asReportinfo = asReportinfoServiceImpl.findByID(jsonObj1.getInt("flag"));
                asCheckresult.setRid(asReportinfo.getId());
                asCheckresult.setPackageUrlHash(asReportinfo.getPackageUrlHash());
                asCheckresult.setResultIndex(3);
                if (jsonObj1.containsKey("safe_type")) {
                    if (jsonObj1.getInt("safe_type") == 0) {
                        asCheckresult.setSafeType(1);
                    } else if (jsonObj1.getInt("safe_type") == 2){
                        asCheckresult.setSafeType(2);
                    } else if (jsonObj1.getInt("safe_type") == 3) {
                        asCheckresult.setSafeType(3);
                    }
                }
                if (jsonObj1.containsKey("virus_name")) {
                    asCheckresult.setVirusName(jsonObj1.getString("virus_name"));
                } else {
                    asCheckresult.setVirusName("");
                }
                
                String virus_desc = "";
                if (jsonObj1.containsKey("virus_desc")) {
                    virus_desc = jsonObj1.getString("virus_desc");
                    virus_desc = virus_desc.replaceAll("[\\[\\]]","");
                    String[] virus_descArray = virus_desc.split(",");
                    for (int m = 0; m < virus_descArray.length; m++) {
                        switch (Integer.parseInt(virus_descArray[m])) {
                        case 1001:
                            virus_desc = virus_desc + "未经用户允许，直接发送短信;";
                            break;
                        case 1002:
                            virus_desc = virus_desc + "未经用户允许，屏蔽短信接收;";
                            break;
                        case 1003:
                            virus_desc = virus_desc + "未经用户允许，禁止接听运营商电话;";
                            break;
                        case 1004:
                            virus_desc = virus_desc + "未经用户允许，后台下载第三方付费程序;";
                            break;
                        case 1005:
                            virus_desc = virus_desc + "未经用户允许，直接拨打电话;";
                            break;
                        case 1006:
                            virus_desc = virus_desc + "在后台悄悄下载内容，消耗手机网络流量;";
                            break;
                        case 1101:
                            virus_desc = virus_desc + "后台偷偷上传用户的手机号码;";
                            break;
                        case 1102:
                            virus_desc = virus_desc + "后台偷偷上传用户手机安装的软件内容;";
                            break;
                        case 1103:
                            virus_desc = virus_desc + "后台偷偷上传用户手机的通话记录;";
                            break;
                        case 1104:
                            virus_desc = virus_desc + "后台偷偷上传用户手机的短信记录;";
                            break;
                        case 1105:
                            virus_desc = virus_desc +"后台偷偷上传用户手机的通讯录;";
                            break;
                        case 1106:
                            virus_desc = virus_desc + "后台偷偷上传用户手机所处位置（如GPS等）;";
                            break;
                        case 1107:
                            virus_desc = virus_desc + "后台偷偷上传用户手机的基本信息（如IMEI号等）;";
                            break;
                        case 1108:
                            virus_desc = virus_desc + "窃取用户短信、电话等信息，并发送至指定邮箱;";
                            break;
                        case 1202:
                            virus_desc = virus_desc + "在后台偷偷往手机上插入推广书签;";
                            break;
                        case 1203:
                            virus_desc = virus_desc + "在后台偷偷往手机上插入推广快捷方式;";
                            break;
                        case 1204:
                            virus_desc = virus_desc + "在后台偷偷在手机上安装第三方程序;";
                            break;
                        case 1205:
                            virus_desc = virus_desc + "未经用户允许，在后台删除指定应用;";
                            break;
                        case 1206:
                            virus_desc = virus_desc + "未经用户允许，打开第三方网页;";
                            break;
                        case 1301:
                            virus_desc = virus_desc + "云端发送给用户手机特定网络指令，用于执行相应恶意行为;";
                            break;
                        case 1401:
                            virus_desc = virus_desc + "利用手机漏洞进行系统提权操作;";
                            break;
                        case 1501:
                            virus_desc = virus_desc + "调用su命令行，调用成功后可执行高危险行为;";
                            break;
                        case 1502:
                            virus_desc = virus_desc + "后台偷偷加载病毒体，通过病毒体执行相应恶意行为;";
                            break;
                        case 1503:
                            virus_desc = virus_desc + "远程向用户手机发送短信指令，控制该手机执行相应恶意行为;";
                            break;
                        case 1601:
                            virus_desc = virus_desc + "后台获取第三方广告内容，并在通知栏弹出;";
                            break;
                        case 1602:
                            virus_desc = virus_desc + "偷偷在手机上安装第三方程序;";
                            break;
                        case 1603:
                            virus_desc = virus_desc + "捆绑病毒;";
                            break;
                        case 1801: 
                            virus_desc = virus_desc + "感染“短信诈骗漏洞”，会伪装为本地联系人发送欺诈短信;";
                            break;
                        case 1901:
                            virus_desc = virus_desc + "恶意广告插件伪造发送本地短信，用于推送欺诈广告;";
                            break;
                        }
                    }
                }
                if (!"".equals(virus_desc)) {
                    asCheckresult.setVirusDesc(virus_desc.substring(0, virus_desc.length() - 1));
                } else {
                    asCheckresult.setVirusDesc(virus_desc);
                }
                
                asCheckresult.setResultDescr("");

                String adinfo = "";
                if (jsonObj1.containsKey("adinfo")) {
                    JSONArray adinfoArray = JSONArray.fromObject(jsonObj1.get("adinfo"));
                    for (int n = 0; n < adinfoArray.size(); n++) {
                        JSONObject adinfoObj = adinfoArray.getJSONObject(n);
                        adinfo = adinfo + adinfoObj.getString("adname");

                        if (adinfoObj.containsKey("adaction") && !"".equals(adinfoObj.getString("adaction").replaceAll("[\\[\\]]",""))) {
                            String adaction = adinfoObj.getString("adaction");
                            adaction = adaction.replaceAll("[\\[\\]]","");
                            String[] adactionArray = adaction.split(",");
                            for (int j = 0; j < adactionArray.length; j++) {
                                switch (Integer.parseInt(adactionArray[j])) {
                                case 1:
                                    adinfo = adinfo + "获取您的手机号，并上传。;";
                                    break;
                                case 2:
                                    adinfo = adinfo + "获取手机所在位置，并上传。;";
                                    break;
                                case 3:
                                    adinfo = adinfo + "获取手机安装软件内容，并上传。;";
                                    break;
                                case 4:
                                    adinfo = adinfo + "获取手机通讯录，并上传。;";
                                    break;
                                case 5:
                                    adinfo = adinfo + "加载DEX;";
                                    break;
                                case 6:
                                    adinfo = adinfo + "启动服务;";
                                    break;
                                case 7:
                                    adinfo = adinfo + "获取IMEI信息;";
                                    break;
                                case 8:
                                    adinfo = adinfo + "读取账户信息;";
                                    break;
                                case 9:
                                    adinfo = adinfo + "设置自启动;";
                                    break;
                                case 10:
                                    adinfo = adinfo + "唤醒;";
                                    break;
                                }
                            }
                        }

                        if (adinfoObj.containsKey("adtype")) {
                            String adtype = adinfoObj.getString("adtype");
                            adtype = adtype.replaceAll("[\\[\\]]","");
                            String[] adtypeArray = adtype.split(",");
                            for (int k = 0; k < adtypeArray.length; k++) {
                                switch (Integer.parseInt(adtypeArray[k])) {
                                case 1:
                                    adinfo = adinfo + "通知栏广告。;";
                                    break;
                                case 2:
                                    adinfo = adinfo + "内嵌广告条。;";
                                    break;
                                case 3:
                                    adinfo = adinfo + "弹窗广告。;";
                                    break;
                                case 4:
                                    adinfo = adinfo + "积分墙广告。;";
                                    break;
                                case 5:
                                    adinfo = adinfo + "伪造短信广告。;";
                                    break;
                                case 6:
                                    adinfo = adinfo + "广告插件自动启动;";
                                    break;
                                }
                            }
                        }
                        if (!"".equals(adinfo)) {
                            asCheckresult.setAdinfo(adinfo.substring(0, adinfo.length() - 1));
                        } else {
                            asCheckresult.setAdinfo(adinfo);
                        }
                    }
                }
                asCheckresult.setScore(0);
                asCheckresult.setSize(0);
                asCheckresult.setPlatform("");
//                asCheckresult.setOfficial();
                asCheckresult.setCreateTime(UtilTools.getTimestamp(0));
                asCheckresult.setLastUpdateTime(UtilTools.getTimestamp(0));

                //AsReportinfo表更新（checkCount，expired，lastUpdateTime）
                AsReportinfo asReportinfoTMP = new AsReportinfo();
                asReportinfoTMP.setId(asReportinfo.getId());
                //安全基本不确定，过期时间统一延后15天
                int expired = 0;
                switch (jsonObj1.getInt("safe_type")) {
                    case 2:
                        expired = Integer.parseInt(SysConfigBean.getProperty("result.safetype.safe")); //推后180天再扫描
                        break;
                    default:
                        expired = Integer.parseInt(SysConfigBean.getProperty("result.safetype.dangerous"));
                        break;
                }
                //Expired过期时间，SQL语句中计算更新
                asReportinfoTMP.setExpired(expired);
                asReportinfoTMP.setCheckTime(UtilTools.getTimestamp(0));
                
                saveScanResult(asCheckresult, asReportinfoTMP);
            } else {
                //检测失败
                logger.info("the error of callback from duba,sid= " + jsonObj1.getInt("flag") + ";errorcode=" + jsonObj1.getInt("error"));
            }
        }
        JSONObject result = new JSONObject();
//        result = "{\"error_code\":\"0\"}";
        result.put("error_code", "0");
	    return result;
	}

}
